package com.myrpc.handler;

import com.myrpc.utils.SerializationUtil;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * Created with IntelliJ IDEA.
 *
 * @Description:
 * @User: weiyi.liu
 * @Date: 2018-06-08
 * @Time: 21:56
 */
public class RpcEncoder extends MessageToByteEncoder {
	private Class genericClass;

	public RpcEncoder(Class genericClass) {
		this.genericClass = genericClass;
	}

	protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) {
		if (genericClass.isInstance(o)) {
			byte[] data = SerializationUtil.serialize(o);
			byteBuf.writeInt(data.length);
			byteBuf.writeBytes(data);
		}
	}
}
